package annotationService.application;


import java.util.List;
import java.util.logging.Logger;

import org.restlet.Context;
import org.restlet.data.CharacterSet;
import org.restlet.data.Form;
import org.restlet.data.Language;
import org.restlet.data.MediaType;
import org.restlet.data.Request;
import org.restlet.data.Response;
import org.restlet.resource.Representation;
import org.restlet.resource.Resource;
import org.restlet.resource.ResourceException;
import org.restlet.resource.StringRepresentation;
import org.restlet.resource.Variant;
import org.restlet.data.Status;

import annotationService.util.JSONSimpler;
import annotationService.util.Utils;

/**
 * VGIResource lets users create VGI objects
 * @author Andres Westermann
 *
 */
public class VGIResource extends Resource {
	Logger log=Logger.getLogger(VGIResource.class.getSimpleName());
	VGIPersistenceManager AnnotationPM=new VGIPersistenceManager("subject");
	final StringRepresentation NO_FOUND_REPR=new StringRepresentation("No found!");
	final StringRepresentation ERR_REPR=new StringRepresentation("something wrong!");
	final String JSON_PARAM="json";
	public VGIResource(
			Context context, 
			Request request, 
			Response response) {
		super(context, request, response);
		this.getVariants().add(new Variant(MediaType.TEXT_PLAIN));
		this.setAvailable(true);
		this.setModifiable(true);
		this.setNegotiateContent(true);
	}
	
	@SuppressWarnings("unchecked")
	@Override
	/**
	 * representing after calling default get handle
	 */
	public Representation represent(Variant variant) throws ResourceException{
		log.info("representing after calling default get handle...");
		Representation result = null;
        if (variant.getMediaType().equals(MediaType.TEXT_PLAIN)) {
        	String subject=getRequest().getResourceRef().getQueryAsForm().getFirstValue("subject");
        	//handle query
        	if (subject!=null && subject.length()>0){
        		VGI example=new VGI();
        		example.setSubject(subject);
        		List queryRet=AnnotationPM.query(example);
        		if (queryRet!=null && queryRet.size()>0){
        			net.sf.json.JSONObject jsonObject = JSONSimpler.FromBeanToJSON(queryRet.get(0));
        			log.info(jsonObject.get("content").toString());
        			result=new StringRepresentation(
        					JSONSimpler.serializeFromBean(queryRet.get(0)),
        					MediaType.APPLICATION_JSON,
        					Language.ALL, 
        					CharacterSet.UTF_8
        				);
        		}
        		else{
        			result=NO_FOUND_REPR;
        		}
        	}
        	else{
        		result=new StringRepresentation(
        				JSONSimpler.serializeFromBeanList(AnnotationPM.list()),
        				MediaType.APPLICATION_JSON,
    					Language.ALL, 
    					CharacterSet.UTF_8
    				);
        	}
        }
        return result;
	}

	
	
	protected StringRepresentation callMethod(String method,String jsonParamVal){
		VGI vgi=(VGI)JSONSimpler.deserializeToBean(jsonParamVal,VGI.class);
		if (vgi!=null){
			String responseText=Utils.callMethodAndGainResponseJSONStr(
					AnnotationPM, 
					method, 
					jsonParamVal,
					VGI.class);
			log.info("response:"+responseText);
			return new StringRepresentation(
					responseText, 
					MediaType.APPLICATION_JSON,
					Language.ALL, 
					CharacterSet.UTF_8
			);
		}
		else{
			return ERR_REPR;
		}
	}
	
	@Override
	/**
	 * handling post in high level
	 * update object
	 */
	public void acceptRepresentation(Representation entity) throws ResourceException{
		log.info("handling post in high level...");
		super.acceptRepresentation(entity);
		getResponse().setStatus(Status.SUCCESS_OK);
		Form f = new Form(entity);
		String jsonParamVal=f.getValues(JSON_PARAM);
		log.info("json param:"+jsonParamVal);
		getResponse().setEntity(callMethod("update",jsonParamVal));
	}
	
	@Override
	/**
	 * handling put in high level
	 * creating a new object
	 */
	public void storeRepresentation(Representation entity) throws ResourceException{
		log.info("handling put in high level...");
		super.storeRepresentation(entity);
		getResponse().setStatus(Status.SUCCESS_CREATED);
		Form f = new Form(entity);
		String jsonParamVal=f.getValues(JSON_PARAM);
		log.info("json param:"+jsonParamVal);
		getResponse().setEntity(callMethod("save",jsonParamVal));
	}
	
	@Override
	/**
	 * handling delete in high level
	 */
	public void removeRepresentations() throws ResourceException{
		log.info("handling delete in high level...");
		super.removeRepresentations();
		getResponse().setStatus(Status.SUCCESS_OK);
		Form f = getRequest().getEntityAsForm();
		String jsonParamVal=f.getValues(JSON_PARAM);
		//hier bekommt der die werte mit jsonParamVal
		log.info("json param:"+jsonParamVal);
		getResponse().setEntity(callMethod("delete",jsonParamVal));
	}
}
